package com.tinshow.web.httpclient;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * Created by randy on 16-12-1.
 */
public class MiaApiRequest{

    public static String getDeafaultHttp(){
        try {
            org.apache.http.client.HttpClient client =  new DefaultHttpClient();
            HostConfiguration host = new HostConfiguration();
            HttpPost post = new HttpPost("http://open.mia.com/api/get?getName=get.brand.list.get");
            post.setHeader("Content_type","application/x-www-form-urlencoded");
            post.setHeader("Connection","keep-alive");
            post.setHeader("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36");
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            list.add(new BasicNameValuePair("method","mia.category.list.get"));
            list.add(new BasicNameValuePair("vendor_key","test_40"));
            list.add(new BasicNameValuePair("timestamp",String.valueOf(new Date().getTime())));
            list.add(new BasicNameValuePair("format","json"));
            list.add(new BasicNameValuePair("secret","f372bed62716ef57012a0d6dba5a0ee8"));
            list.add(new BasicNameValuePair("version","1.0"));
            list.add(new BasicNameValuePair("url","http://gw-test.api.miyabaobei.com/openapi/app"));
            post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            String result = "";
            if(response.getStatusLine().getStatusCode() == 200){
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
                return result;
            }
        }catch (Exception e){
            e.printStackTrace();;
        }
        return null;
    }

//    public static void main(String[] args){
//        getExcel();
//    }

    public static Map<String,String> parseHtml(){
        String response = getDeafaultHttp();
        Map<String,String> brandList = new HashMap<String,String>();
        Document doc = Jsoup.parse(response);
        Element urlId = doc.getElementById("urlId");
        String text = urlId.text().substring(110,urlId.text().length()).replaceAll(" ","").replaceAll("=>","").replaceAll("Array","");
        String[] text2 = text.split("]\n" +
                "\\(");
//        for (int i = 0; i < text2.length; i++){
//            System.out.print(text2[i]);
//        }
        for (int i = 0; i <= 1596; i++){
            text = text.replaceAll("\\["+(i)+"\\]","");
            if(i == 1596){
                String[] text1 = text.replaceAll("\\)","").split("\\[request_id\\]")[0].split("\\(");
                for (int j =0;j<text1.length;j++){
//                    System.out.print(i+"=============="+text1[j]);
                    String[] text3 = text1[j].replaceAll("\\[category_id\\]","").split("\\[name\\]");
                    if(text3.length == 2){
                        String categoryId = text3[0];
                        String name = text3[1].split("\\[parent_id\\]")[0];
                        String parentId = text3[1].split("\\[parent_id\\]")[1].split("\\[is_leaf\\]")[0];
                        String isLeaf = text3[1].split("\\[parent_id\\]")[1].split("\\[is_leaf\\]")[1];
                        System.out.print(categoryId+"===="+name+"===="+parentId+"===="+isLeaf);
                        brandList.put(String.valueOf(j),categoryId+"="+name+"="+parentId+"="+isLeaf);

                    }

                }
            }
        }
        return brandList;
    }

    public static void getExcel(){
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");

        // 设置excel每列宽度
        sheet.setColumnWidth(0, 4000);
        sheet.setColumnWidth(1, 3500);
        // 创建字体样式
        HSSFFont font = wb.createFont();
        font.setFontName("Verdana");
        font.setBoldweight((short) 100);
        font.setFontHeight((short) 300);

        // 创建单元格样式
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);


        style.setFont(font);// 设置字体
        // 创建Excel的sheet的一行
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("categoryId");
        row.createCell(1).setCellValue("name");
        row.createCell(2).setCellValue("parentId");
        row.createCell(3).setCellValue("isLeaf");
            // 创建一个Excel的单元格

        for(Map.Entry<String, String> entry:parseHtml().entrySet()){
            row = sheet.createRow(Integer.parseInt(entry.getKey()));
            String[] entry1 = entry.getValue().split("=");
            for (int i = 0; i<entry1.length;i++){
                HSSFCell cell = row.createCell(i);

//                // 设置单元格内容格式
//                HSSFCellStyle style1 = wb.createCellStyle();
//                style1.setDataFormat(HSSFDataFormat.getBuiltinFormat("h:mm:ss"));
//
//                style1.setWrapText(true);// 自动换行
//
//                row = sheet.createRow(1);
//
//                // 设置单元格的样式格式

//                cell.setCellStyle(style1);
                cell.setCellValue(entry1[i]);
            }
        }
        try {
            FileOutputStream os = new FileOutputStream("/home/randy/文档/category.xlsx");
            wb.write(os);
            os.close();
        }catch(IOException e){
            e.printStackTrace();;
        }


    }

}
